var express = require("express");
var router = express.Router();
var userservice = require("../service/userservice");
let crypto = require("crypto");
let jwt = require("jsonwebtoken");
/* GET users listing. */
router.get("/", function (req, res, next) {
  res.send("respond with a resource");
});
//pc //webapp  //apk //小程序   //cs
router.post("/add", async (req, res, next) => {
  let { username, userpwd, usertype } = req.body;
  // let md5 = crypto.createHash("md5");
  // userpwd = md5.update(userpwd).digest("hex");
  await userservice.add({ username, userpwd, usertype });
});

router.post("/login", async (req, res, next) => {
  let { username, userpwd } = req.body;
  let md5 = crypto.createHash("md5");
  userpwd = md5.update(userpwd).digest("hex");

  let result = await userservice.query({ username, userpwd });
  if (result.length) {
    let info = result[0]; //用户信息
    let obj = {
      username: info.username,
      userid: info._id,
      usertype: info.usertype,
    };

    let token = jwt.sign(obj, "abc", { expiresIn: 1000 * 60 * 30 });

    let menuList = []; //菜单的集合

    if (info.usertype == 1) {
      //老师
      menuList = [
        { path: "/main/leave", msg: "请假管理", com: "leave" },
        { path: "/main/student", msg: "学生管理", com: "student" },
      ];
    } else {
      menuList = [{ path: "/main/addleave", msg: "请假页面", com: "addleave" }];
    }
    res.json({
      code: 200,
      msg: "登录成功", //登录成功以后 把用户相关的信息 加密以后返回前端
      token,
      menuList,
    });
  } else {
    res.json({
      code: 500,
      msg: "用户和密码不匹配",
    });
  }
});
router.get("/getmenu", (req, res, next) => {
  let token = req.headers.token; //放在头部

  jwt.verify(token, "abc", (err, info) => {

    if (err) {
      res.json({
        code: 500,
        msg: "token解析异常",
        err,
      });
    } else {
      let usertype = info.usertype; //获取用户类别

      let menuList = []; //菜单的集合

      if (usertype == 1) {
        //老师
        menuList = [
          { path: "leave", msg: "请假管理", com: "leave" },
          { path: "student", msg: "学生管理", com: "student" },
        ];
      } else {
        menuList = [
          { path: "addleave", msg: "请假页面", com: "addleave" },
        ];
      }

      res.json({
        code: 200,
        menuList,
      });
    }
  });
});
router.get('/list',(req,res,next)=>{ //老师处理请假
  let token = req.headers.token;
  jwt.verify(token,'abc',async(err,info)=>{
      if(err){
          res.json({
              code:500,
              msg:'token解析异常'
          })
      }else{
         let {usertype} = info
          if (usertype == 1) {
           let result = await userservice.query({usertype:2})
           res.json({
            code: 200,
            result,
          });
        
         }else{
          res.json({
              code:500,
              msg:'权限不够'
          })
         }
      }
  })
})
module.exports = router;
